package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.SpliceAdapter;
import flc.ast.databinding.ActivityVideoSpliceBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;

public class VideoSpliceActivity extends BaseAc<ActivityVideoSpliceBinding> {

    public static List<String> listPath = new ArrayList<>();
    private long videoLength;
    private int playNum = 0;
    private String savePath = "";
    private Dialog myTipDialog;
    private SpliceAdapter splitAdapter;
    private int selPosition = 0;


    @Override
    protected int onCreate() {
        return R.layout.activity_video_splice;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoSpliceBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoSpliceSave.setOnClickListener(this);
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.ivVideoSpliceAdd.setOnClickListener(this);
        mDataBinding.tvGenerate.setOnClickListener(this);
        mDataBinding.rvVideoSpliceList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        splitAdapter = new SpliceAdapter();
        mDataBinding.rvVideoSpliceList.setAdapter(splitAdapter);
        splitAdapter.addChildClickViewIds(R.id.ivSpliceItemImg, R.id.ivSpliceItemExchange);
        splitAdapter.setOnItemClickListener(this);
        splitAdapter.setOnItemChildClickListener(this);
        //提示弹框
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        if (FastClickUtil.isFastClick()) return;
        switch (v.getId()){
            case R.id.ivVideoPlay:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting00);
                    mDataBinding.videoView.start();
                }
                break;
            case R.id.ivVideoSpliceAdd://添加
                Intent intent = new Intent(this, SelImportVideoActivity.class);
                intent.putExtra(Content.Again, "Again");
                startActivityForResult(intent, Content.SPLIT_ADD);
                break;
            case R.id.tvGenerate://开始拼接
                if (listPath.size()<2){
                    ToastUtils.showShort(getString(R.string.please_sel_two_video));
                    return;
                }
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
                    mDataBinding.videoView.pause();
                }
                splitVideo();
                break;
            case R.id.ivVideoSpliceSave://保存
                if (TextUtils.isEmpty(savePath)) {
                    ToastUtils.showShort(R.string.please_video_splice);
                    return;
                }
                saveVideo();
                break;
            //提示弹框
            case R.id.tvDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.tvDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()){
            case R.id.ivSpliceItemImg://更换视频
                selPosition = position;
                Intent intent = new Intent(this, SelImportVideoActivity.class);
                intent.putExtra(Content.Again, "Again");
                startActivityForResult(intent, Content.SPLIT_REPLACE);
                break;
            case R.id.ivSpliceItemExchange://交换视频
                Collections.swap(listPath, position, position + 1);
                updateData();
                setPlayer();
                break;
        }
    }

    @Override
    protected void initData() {
        if (listPath.size() == 0) return;
        updateData();
        //设置播放器
        setPlayer();
    }

    //更新集合
    private void updateData() {
        splitAdapter.setList(listPath);
        splitAdapter.setPos(listPath.size() - 1);
    }

    //设置播放器
    private void setPlayer() {
        playNum = 0;
        splitAdapter.notifyDataSetChanged();
        videoLength = MediaUtil.getDuration(listPath.get(0));
        //设置播放器
        mDataBinding.videoView.setVideoPath(listPath.get(0));
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                playNum++;
                if (playNum < listPath.size()) {//继续播放下一个视频
                    splitAdapter.notifyDataSetChanged();
                    videoLength = MediaUtil.getDuration(listPath.get(playNum));
                    mDataBinding.videoView.setVideoPath(listPath.get(playNum));
                    mDataBinding.videoView.seekTo(1);
                    mDataBinding.videoView.start();
                } else {//重新播放
                    setPlayer();
                }
            }
        });
        //开始播放视频
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting00);
        mDataBinding.videoView.start();
    }

    //拼接视频
    private void splitVideo() {
        EditorHolder.editor().videoMerge(listPath, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.generate_suc));
                savePath = outFilePath;
                mDataBinding.videoView.setVideoPath(outFilePath);
                mDataBinding.videoView.seekTo(1);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting00);
                mDataBinding.videoView.start();
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(R.string.split_def);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.split_ing) + progress + "%");
            }
        });
    }

    //保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_video_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, savePath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String path = data.getStringExtra(Content.videoPath);
            if (requestCode == Content.SPLIT_REPLACE) {
                listPath.set(selPosition, path);
            } else if (requestCode == Content.SPLIT_ADD) {
                listPath.add(0,path);
            }
            updateData();
            setPlayer();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
        mDataBinding.videoView.pause();
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y=50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogTipCancel);
        TextView right = inflate.findViewById(R.id.tvDialogTipRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}